package com.quanzhi.openapi.host;

import com.quanzhi.openapi.entity.HostInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
public class HostAspect {

    @Autowired
    private MongoTemplate mongoTemplate;


    private static final Logger logger = LoggerFactory.getLogger(HostAspect.class);

    // 使用 ThreadLocal 存储 host 信息
    private static final ThreadLocal<String> hostHolder = new ThreadLocal<>();

    @Before("@annotation(com.quanzhi.openapi.host.HostRequired)")
    public void beforeMethod(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String host = request.getHeader("Host");
        HostInfo hostInfo = new HostInfo(host);
        mongoTemplate.save(hostInfo);
        hostHolder.set(host);
        logger.info("Extracted Host: {}", host);
    }

    public static String getHost() {
        return hostHolder.get();
    }

    // 清理 ThreadLocal 以防内存泄漏
    @After("@annotation(com.quanzhi.openapi.host.HostRequired)")
    public void afterMethod() {
        hostHolder.remove();
    }
}
